﻿using AppSocketModel;
using AppSocketService.Account;
using BCGPSCommon;
using BCGPSMongoData;
using System;
using System.Collections.Generic; 
using System.Linq; 

namespace AppSocketService.RealSendData
{
    public  class RealSendDataHistoryService : ServiceBase, IRealSendDataHistoryService
    {
        private MongoDBCommand<RealSendDataDto> mongoCommand = new MongoDBCommand<RealSendDataDto>("CmdSendTimeSpanRealHistory");
        private readonly IRedisService redisService;
        private readonly AccountDto CurrentAccount;
        public RealSendDataHistoryService(IClaimsAccessor claimsAccesso, IRedisService redisService, IAccountService accountService, ISystemAccountService systemAccountService) : base(claimsAccesso)
        {
            this.redisService = redisService; 
            if (claimsAccesso.AccountRole == AccountRole.SYSTEM)
                CurrentAccount = systemAccountService.GetCurrentAccount().AsAccountDto();
            else
                CurrentAccount = accountService.GetCurrentAccount();
        } 
        public bool SetCmd(string imei, int second)
        {
            if (string.IsNullOrWhiteSpace(imei) || imei.Length < 15)
                throw new ArgumentException("请输入正确的IMEI编号!");
            if (second > 100 || second < 1)
                throw new ArgumentException("发送时间不能设置大于100秒小于1秒!");


            RealSendDataDto realSendDataDto = new RealSendDataDto();
            realSendDataDto.CmdDateTime = MongoDBDateTime.GetNowUtc();
            realSendDataDto.IMEI = imei;
            realSendDataDto.CmdCode = ((int)GpsCmdCode.SendTimeSpanReal).ToString();
            realSendDataDto.CmdCodeStr = GpsCmdCode.SendTimeSpanReal.ToString();
            realSendDataDto.CmdParamer = second.ToString();
            realSendDataDto.CmdToward = "Send";

            realSendDataDto.CompanyId = CurrentAccount.CompanyId;
            realSendDataDto.AccountId = CurrentAccount.AccountId;
            realSendDataDto.AccountCode = CurrentAccount.AccountCode;
            realSendDataDto.AccountRole = CurrentAccount.AccountRole;

            mongoCommand.InsertDocumentAsync(realSendDataDto).GetAwaiter().GetResult();

            redisService.AddAsync(BCGPSCommon.GeneralContainer.RedisNameSpaceIMEISendCmd + imei, "$CMD$3$" + second + "$");

            return true;
        }

        public PageableList<RealSendDataDto> GetList(string imei, DateTime start, DateTime end, bool desc, int index, int size)
        {
            index = index > 0 ? index - 1 : 0;
            if (end.Hour == 0 && end.Minute == 0 && end.Second == 0)
                end = end.AddDays(1);
            start = MongoDBDateTime.GetUtc(start);
            end = MongoDBDateTime.GetUtc(end);
            return mongoCommand.SelectDocumentsAsync(s => s.IMEI == imei && s.CmdDateTime > start && s.CmdDateTime < end, s => s.CmdDateTime, desc, index * size, size).GetAwaiter().GetResult();
        }

    }
}
